package net.pimpas.web.jsf.components.validators.regex.custom;

import javax.faces.context.FacesContext;

import net.pimpas.resourcebundle.serviceprovider.ResourceBundleServiceProviderType;
import net.pimpas.web.jsf.components.validators.PimpasValidator;
import net.pimpas.web.jsf.components.validators.exception.PimpasValidatorTagException;
import net.pimpas.web.jsf.components.validators.regex.RegexValidator;
import net.pimpas.web.jsf.components.validators.regex.RegexValidatorTag;
import net.pimpas.web.jsf.util.ComponentUtils;

public class CustomRegexValidatorTag extends RegexValidatorTag {

	private static final long serialVersionUID = 1L;
	private String regex;
	
	@Override
	protected void validate(FacesContext context, RegexValidator validator) throws PimpasValidatorTagException {
		String rgx = this.getRegex();
		if(rgx != null && ComponentUtils.isOnlyValueBinding(rgx))
			rgx = (String) context.getApplication().createValueBinding(rgx).getValue(context);
		
		if(rgx == null || "".equals(rgx)) {
			try {
				throw new PimpasValidatorTagException(
						this.getBundle().getMessage(PimpasValidator.class, "propertyNull", ResourceBundleServiceProviderType.ERROR, "regex", "RegexValidator")
						);
			} catch (Throwable e) {
				throw new PimpasValidatorTagException(e);
			}
		}
		
		CustomRegexValidator crv = (CustomRegexValidator) validator;
		crv.setRegex(new CustomRegex(rgx));
	}

	public String getRegex() {
		return regex;
	}

	public void setRegex(String regex) {
		this.regex = regex;
	}
	
	@Override
	public String getValidatorID() {
		return CustomRegexValidator.VALIDATOR_ID;
	}
}